<template>
  <view class="image-c" @click="handleClickImg">
    <image :src="src" class="img-wrapper" />
    <view class="plus" v-if="!src && !preview">+</view>
  </view>
</template>

<script>
import { getToken } from "@/utils/auth";
export default {
  name: "xh-image",
  props: {
    src: {
      type: String,
    },
    preview: {
      type: Boolean,
      default: false,
    },
  },
  methods: {
    handleClickImg() {
      // 预览模式
      if (this.preview) {
        // eslint-disable-next-line no-undef
        uni.previewImage({
          current: this.src,
          urls: [this.src],
        });
        return;
      }
      // eslint-disable-next-line no-undef
      uni.chooseImage({
        success: (chooseImageRes) => {
          const tempFilePaths = chooseImageRes.tempFilePaths;
          // eslint-disable-next-line no-undef
          uni.uploadFile({
            url: "https://www.jxgl123.com/prod-api/common/upload", //仅为示例，非真实的接口地址
            filePath: tempFilePaths[0],
            name: "file",
            header: {
              Authorization: "Bearer " + getToken(),
              "Content-type": "multipart/form-data;",
            },
            // formData: {
            // 	user: 'test',
            // },
            success: (res) => {
              const { data } = res;
              const { url } = JSON.parse(data);
              this.$emit("onSuccess", url);
            },
          });
        },
      });
    },
  },
};
</script>

<style scoped lang="scss">
.image-c {
  position: relative;
  display: inline-flex;
  .img-wrapper {
    height: 60px;
    width: 60px;
    border: 1px solid $uni-border-color;
  }
  .plus {
    font-size: 25px;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
  }
}
</style>
